package es.project.sien7e.main.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import es.project.sien7e.main.model.Usuario;
import es.project.sien7e.main.services.DAOService;

@Controller
@RequestMapping("inicio")
public class InicioController {
	private DAOService daoService;

	@Autowired
	public void setDaoService(DAOService daoService) {
		this.daoService = daoService;
	}

	@RequestMapping("/")
	public String inicio(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws Exception {
		String resultado = "inicio";
		UserService userService = UserServiceFactory.getUserService();
		String thisURL = request.getRequestURI() + "acceso";
		session.setAttribute("singin", userService.createLoginURL(thisURL));
		session.setAttribute("singout", userService.createLogoutURL(thisURL));
		return resultado;
	}

	@RequestMapping("/acceso")
	public String acceso(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws Exception {
		String resultado = "inicio";
		UserService userService = UserServiceFactory.getUserService();
		User usuario = userService.getCurrentUser();
		if (usuario != null) {
			Usuario obj = new Usuario();
			obj.setEmail(usuario.getEmail());
			obj.setLogin(usuario.getNickname());
			if (daoService.compruebaUsuario(obj) == null)
				daoService.insertaUsuario(obj);
			session.setAttribute("usuario", usuario);
		} else {
			session.removeAttribute("usuario");
		}
		return resultado;
	}
}
